/**@odoo-module**/
import {registry} from "@web/core/registry";
import {useService} from "@web/core/utils/hooks";
import {FileInput} from "@web/core/file_input/file_input";
import {useX2ManyCrud} from "@web/views/fields/relational_utils";

const {Component, useState, useRef} = owl;

export class Many2manyPreview extends Component {
    setup() {
        this.orm = useService("orm");
        this.notification = useService("notification");
        this.operations = useX2ManyCrud(() => this.props.value, true);
    }

    // 计算函数
    get files() {
        return this.props.value.records.map((record) => record.data);
    }

    getUrl(id) {
        return "/web/content/" + id + "?download=true";
    }

    getId(attachment) {
        // 获取自定义属性
        return attachment.attributes[0].value
    }


    preview(ev) {
        // 禁止冒泡
        ev.stopPropagation()
        var self = this;
        var fieldId = self.getId(ev.currentTarget);
        console.log(fieldId)
        // 通过Jquery获取元素
        const $targetElement = $(ev.target)

        // 发起远程请求
        const xhr = new XMLHttpRequest()
        const param = {
            'id': fieldId
        }
        const params = new URLSearchParams(param)
        xhr.open('GET', `/get/fileUrl?${params}`)
        xhr.addEventListener('loadend', () => {
            const data = xhr.response
            const objData = JSON.parse(data)
            const url = objData.url
            const preview_url = objData.preview_url
            console.log(url)
            // 追加动态Html代码
            $targetElement.append(`
      <div class="zPDF_iframe">
            <div class="pdc_close btn btn-secondary btn-lg" style="color:black">关闭</div>&nbsp;&nbsp;&nbsp;
            <div class="btn btn-secondary btn-lg"><a href="${url}" style="text-decoration: none; color: black">下载</a></div><br>
            <iframe  class="zPDF" scrolling="no" id="main" name="main" frameborder="0"  style="min-height:600px;width:1000px;height:100%;m" src="${preview_url}"></iframe>
      </div>
      `)
            $targetElement.on('click', '.zPDF_iframe', (ev) => {
                // 禁止冒泡
                ev.stopPropagation()
            })
            $targetElement.on('click', '.zPDF_iframe>.pdc_close', function (ev) {
                ev.stopPropagation();
                $(this).parent('.zPDF_iframe').remove();
            })
        })
        xhr.send()
        console.log(url)

    }

    getExtension(file) {
        return file.name.replace(/^.*\./, "");
    }

    async onFileUploaded(files) {
        for (const file of files) {
            if (file.error) {
                return this.notification.add(file.error, {
                    title: this.env._t("Uploading error"),
                    type: "danger",
                });
            }
            await this.operations.saveRecord([file.id]);
        }
    }

    async onFileRemove(deleteId) {
        const record = this.props.value.records.find((record) => record.data.id === deleteId);
        this.operations.removeRecord(record);
    }
}

// 静态属性
Many2manyPreview.template = "base.Many2manyPreview";
Many2manyPreview.components = {
    FileInput,
}
Many2manyPreview.supportedTypes = ["many2many"];
Many2manyPreview.fieldsToFetch = {
    name: {type: "char"},
    mimetype: {type: "char"}
};
Many2manyPreview.props = {
    id: {type: String, optional: true},
    name: {type: String, optional: true},
    readonly: {type: Boolean, optional: true},
    record: {type: Object, optional: true},
    type: {type: String, optional: true},
    update: {type: Function, optional: true},
    value: true,
    decorations: {type: Object, optional: true},
    setDirty: {type: Function, optional: true},
    acceptedFileExtensions: {type: String, optional: true},
    className: {type: String, optional: true},
    uploadText: {type: String, optional: true},
}

Many2manyPreview.isEmpty = () => false;
Many2manyPreview.extractProps = ({attrs, field}) => {
    return {
        acceptedFileExtensions: attrs.options.accepted_file_extensions,
        className: attrs.class,
        uploadText: field.string,
    };
};
registry.category("fields").add("many2many_preview", Many2manyPreview);